-- Drunk
-- Created by chengb Jul/29/2016
-- 醉汉

-- 初始化
function initDrunk(self)
    self.item:removeAllChildren();

    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            local function okFunc()
                local dbase = DungeonM.queryElement(self.gridData.element, "dbase");
                local classId = dbase["submit_item"];
                if type(classId) == 'number' then
                    if ItemM.getAmount(ME.user, classId) <= 0 then
                        -- 缺少提交的道具
                        alert(getLocStr("lack_submit_item"));
                        return;
                    end
                elseif type(classId) == "table" then
                    -- 配置的是一个列表，则检查是否拥有其中任意一种道具
                    local isOk = false;
                    for _, id in ipairs(classId) do
                        if DungeonServiceM.getDungeonItemAmount(id) > 0 then
                            isOk = true;
                            break;
                        end
                    end
                    if not isOk then
                        -- 道具不足
                        alert(getLocStr("lack_submit_item"));
                        return;
                    end
                end

                -- 醉汉消失
                if DungeonActionM.go("drunk_disappear", self.gridData:getPos()) then
                    local tip = buildingInfo["bonus_tip"];
                    alert(tip);
                    playBuildingDisappear(self);
                end
            end
            self:openBuildingView(okFunc);
        end
    end

    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);

    -- 呼吸
    self.needAnimation = true;

    -- 如果醉汉已经消失，则格子隐藏
    local isVisible = not BraveVSDragonM.isDrunkDisapear(self.gridData.class);
    self.icon:setVisible(isVisible);
end
